using MediatR;
using admin.application.Notifications;
using admin.core.Entities.App;
using admin.core.Repositories;
using System.Data;
using Dapper;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace admin.application.Handler
{
    public class UserRegisteredEventHandler : INotificationHandler<UserRegisteredNotification>
    {
        private readonly IRepository<AppRole> _roleRepo;
        private readonly IDbConnection _dbConnection;
        private readonly ILogger<UserRegisteredEventHandler> _logger;

        public UserRegisteredEventHandler(IRepository<AppRole> roleRepo, IDbConnection dbConnection, ILogger<UserRegisteredEventHandler> logger)
        {
            _roleRepo = roleRepo;
            _dbConnection = dbConnection;
            _logger = logger;
        }

        public async Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken)
        {
            var userId = notification.Event.UserId;
            _logger.LogInformation("处理用户注册事件，用户ID: {UserId}", userId);
            var roles = await _roleRepo.GetAllAsync();
            var defaultRole = roles.FirstOrDefault(r => r.RoleName == "User" || r.RoleName == "用户");
            if (defaultRole == null)
            {
                _logger.LogWarning("未找到默认角色，用户ID: {UserId}", userId);
                return;
            }
            var sql = "INSERT INTO \"AppRoleAppUser\" (\"UsersId\", \"RolesId\") VALUES (@UserId, @RoleId) ON CONFLICT DO NOTHING;";
            await _dbConnection.ExecuteAsync(sql, new { UserId = userId, RoleId = defaultRole.Id });
            _logger.LogInformation("已为用户 {UserId} 分配默认角色 {RoleId}", userId, defaultRole.Id);
        }
    }
} 